package com.scr.apiinterface.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scr.apiclientsdk.utils.SignUtils;
import com.scr.apiinterface.domain.User;
import com.scr.apiinterface.mapper.UserMapper;
import com.scr.apiinterface.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;

/**
 * @author scr
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-12-02 15:54:59
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getUsernameByPost(User user, HttpServletRequest request) {
        String accessKey = request.getHeader("accessKey");
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String body = request.getHeader("body");
        User curUser = userMapper.selectById(user.getId());
        if (!accessKey.equals(curUser.getAccesskey())) {
            throw new RuntimeException("无权限");
        }
        if (Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }
        // 时间和当前时间不能超过 5 分钟
        // 获取当前时间戳（假设为秒级时间戳）
        long currentTime = Instant.now().getEpochSecond();
        // 假设时间戳的有效期为 5 分钟（300 秒）
        long timestampThreshold = Long.parseLong(timestamp) + 300;
        if (currentTime > timestampThreshold) {
            throw new RuntimeException("请求已过期");
        }

        String serverSign = SignUtils.genSign(body, curUser.getSecretkey());
        if (!sign.equals(serverSign)) {
            throw new RuntimeException("无权限");
        }
        // todo 调用次数 + 1 invokeCount
        String result = "POST 用户名字是" + user.getUsername();
        return result;
    }
}




